<template>
  <view>
    <scroll-view scroll-y class="Pet_scroll">

      <van-cell title="更换头像">
        <view slot="right-icon" class="pet_image" @click="getImg(Pet.imgArr3,'touxiang')">
          <image v-if="Pet.imgArr3.length === 0" src="http://qichong-1256206693-1256206693.cos.ap-nanjing.myqcloud.com/upload/20210617/a1b0aedabc466612a506a75eda513e72.png" mode="aspectFill"></image>
          <block v-else v-for="(item,i) in Pet.imgArr3" :key="i">
            <image :src="item.link" mode="aspectFill"></image>
          </block>
        </view>
        <van-icon slot="right-icon" name="arrow" class="custom-icon" />
      </van-cell>

      <van-cell-group>
        <van-field :model:value="Pet.nickname" maxlength="10" label="编辑昵称" placeholder="昵称不得超过十个字符" input-align="right"
          @blur="Changenickname" />
      </van-cell-group>

      <van-cell title="性别" is-link :value="gender" @click="Pet_gender" />

      <van-cell-group>
        <van-cell title="绑定手机号" :value="Pet.phone">
          <button v-if="Pet.phone === ''" class="binding_button" type="default" slot="right-icon"
            open-type="getPhoneNumber" @getphonenumber="bindPhone">一键绑定</button>

          <view v-else>{{Pet.phone}}</view>
        </van-cell>
      </van-cell-group>

      <van-cell title="生日" is-link :value="Pet.time | dateFormat" @click="Pet_Data" />

      <van-cell-group>
        <van-field :model:value="Pet.region" maxlength="10" label="所在地" input-align="right" placeholder="请输入所在地"
          @blur="Changeregion" />
      </van-cell-group>

      <view class="new_pet">
        <button type="success" class="new_pet_button" @click="UpdateArchives">保存</button>
      </view>

    </scroll-view>

    <!-- 性别 -->
    <van-action-sheet :show="Gendershow" :actions="actions" cancel-text="取消" @select="GenderSelect"
      @cancel="GenderCancel" />

    <!-- 时间弹出 -->
    <van-popup :show="Datashow" round position="bottom" custom-style="height: 50%;">
      <van-datetime-picker type="date" :value="currentDate" :max-date="maxDate" @cancel="Pet_CancelData"
        @confirm="Pet_ConfirmData" :formatter="formatter" />
    </van-popup>


  </view>
</template>

<script>
  import {
    TENANT_ID
  } from '@/config/const.js'
  import {
    bindWxPhone,
    getUserInfo,
    getUserUpdate,
    removeFile
  } from "@/api/user.js";
  import {
    mapGetters,
    mapActions,
    mapState,
    mapMutations
  } from 'vuex'
  export default {
    data() {
      return {
        Pet: {
          // 宠物昵称
          nickname: '',
          // 性别
          actionsValue: 1,
          // 头像
          imgArr3: [],
          // 手机号
          phone: '',
          // 出生日期
          time: '2000-01-01',
          // 所在地
          region: ''
        },
        gender: '请选择',
        // 性别
        Gendershow: false,
        actions: [{
            name: 'GG',
            value: 0
          },
          {
            name: 'MM',
            value: 1
          },
        ],
        // 弹出框
        Datashow: false,
        currentDate: new Date().getTime(),
        maxDate: new Date().getTime(),
        formatter(type, value) {
          if (type === 'year') {
            return `${value}年`;
          } else if (type === 'month') {
            return `${value}月`;
          }
          return value;
        },
      };
    },
    computed: {
      ...mapGetters('m_user',['userInfo'])
    },
    onLoad() {
      this.UpdateInfo()
    },
    filters: {
      //过滤器 用于格式化时间
      dateFormat: function(value) {
        var date = new Date(value); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var year = date.getFullYear();
        var month = ("0" + (date.getMonth() + 1)).slice(-2);
        var sdate = ("0" + date.getDate()).slice(-2);
        // 拼接
        var result = year + "-" + month + "-" + sdate
        // 返回
        return result;
      },
    },
    methods: {
      ...mapActions('m_user',['getCurrentLocation', 'getCode', 'getUserInfo']),
      Pet_gender() {
        this.Gendershow = true
      },
      // 回显
      UpdateInfo() {
        getUserInfo().then(res => {
          // console.log(res)
          this.Pet.nickname = res.data.name
          this.Pet.imgArr3 = res.data.avatar !== '' ? this.imgArrArr(res.data.avatar.split(',')) : [],
          this.Pet.time = res.data.birthday.substr(0, 10)
          this.gender = res.data.sex == '0' ? 'GG' : 'MM'
          this.Pet.region = res.data.area
          this.Pet.phone = res.data.phone
        })
      },
      // 性别
      GenderSelect(e) {
        this.gender = e.detail.name
        this.Pet.actionsValue = e.detail.value
        this.Gendershow = false
      },
      // 
      GenderCancel() {
        this.Gendershow = false
        this.Sterilizationshow = false
      },
      getImg(imageData, type) {
        let self = this;
        self.$util.uploadImageOne('blade-resource/oss/endpoint/put-file', function(res) {
          // console.log(res)
          const data = JSON.parse(res)
          if (type) {
            if (imageData.length !== 0) {
              let imgInfo = {
                link: data.data.link,
                name: data.data.name
              }
              imageData.push(imgInfo)
              self.CloseImage(imageData, 0)
              return
            }
            imageData.push(data.data)
          }
          // console.log(data)
          imageData.push(data.data)
        });
      },
      CloseImage(data, i) {
        // console.log(event)
        // console.log(this.Pet.imgArr[i].name.substr(7))
        removeFile(data[i].name).then(res => {
          // console.log(res)
          if (res.code !== 200) return uni.showToast({
            title: "删除失败"
          })
          data.splice(i, 1)
        })
      },
      Pet_Data() {
        this.Datashow = true
      },
      Pet_ConfirmData(e) {
        this.Datashow = false
        console.log(e)

        this.Pet.time = e.detail
      },
      Pet_CancelData() {
        this.Datashow = false
      },
      Changenickname(e) {
        this.Pet.nickname = e.target.value
      },
      Changeregion(e) {
        this.Pet.region = e.target.value
      },
      // 更新
      async UpdateArchives() {

        const imgArr3 = []
        this.Pet.imgArr3.forEach(item => {
          imgArr3.push(item.link)
        })

        const user = {
          avatar: imgArr3.join(''),
          name: this.Pet.nickname,
          phone: this.Pet.phone,
          birthday: this.$util.formatDateTime(new Date(this.Pet.time)),
          sex: this.Pet.actionsValue,
          id: this.userInfo.id,
          area: this.Pet.region
        }

        console.log(user)

        getUserUpdate(user).then(res => {
          // console.log(res)
          this.$store.commit('setUserInfo', user)
          uni.navigateBack()
        }).catch(err => err)



      },// 绑定手机号
      bindPhone(e) {
        let that = this;
        this.getCode().then(code => {
          bindWxPhone(
            e.detail.encryptedData,
            e.detail.iv,
            code
          ).then(res => {
            // console.log(res.data)
            that.Pet.phone = res.data
            if (res.success) {
              that.getUserInfo();
            }
          }, error => {
            // console.log(error);
          });
        }).catch(res => {
          // console.log(res);
        });
      },
      
      // 优化 从后台回显的图片数据
      imgArrArr(num) {
        const img = []
        num.forEach(item => {
          img.push({
            link: item,
            name: item.substr(50)
          })
        })
        return img
      }
    }
  }
</script>

<style lang="scss">
  /deep/ .van-cell {
    padding-top: 40rpx !important;
    padding-bottom: 40rpx !important;
    align-items: center;

    /deep/ .van-cell__title {
      font-size: 34rpx;
      line-height: 64rpx;
    }
  }

  .binding_button {
    width: 150rpx;
    height: 50rpx;
    border-radius: 50rpx;
    line-height: 50rpx;
    background-color: #FDD338 !important;
    border: none;
    font-size: 22rpx;
    color: rgba(61, 61, 61, 0.6);
  }
  .pet_image {
    width: 128rpx;
    height: 128rpx;
    margin-right: 20rpx;
    border-radius: 50%;
    overflow: hidden;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .new_pet {
    position: fixed;
    bottom: 0;
    padding: 24rpx;
    width: 750rpx;
    height: 128rpx;
    box-sizing: border-box;
    background-color: #fff;

    .new_pet_button {
      width: 702rpx;
      height: 82rpx;
      background-color: #FDD338;
      border-radius: 6px;
      color: rgba(61, 61, 61, 1);
      line-height: 82rpx;
      border-radius: 82rpx;
      font-size: 16px;
      font-weight: 500;
    }
  }
</style>
